<template>
	<view class="container">
		<view class="header">
			<u-icon name="arrow-leftward" size="20" @click="goBack"></u-icon>
			<text class="title"> {{ mode }} </text>
			<u-icon name="checkmark" size="20" @click="onSaveClothes"></u-icon>
		</view>
		<u--form labelPosition="left" :model="clothesInfo" ref="uForm" :key="refreshKey">
			<view class="yy-card">
				<u-form-item label="图片" :borderBottom="false" ref="main_image">
					<u-upload :fileList="clothesInfo.main_images" @afterRead="afterReadMainImage" imageMode="aspectFit"
						@delete="deleteMainImage" name="main_images" :maxCount="1" width="100" height="100"
						:key="mainImageKey" style="display: flex; flex-wrap: wrap; align-content: flex-end;">
					</u-upload>
				</u-form-item>
				<view style="display: flex; padding-bottom: 10px">
					<u-button @click="removeBackground" type="primary" size="mini" plain
						style="margin-top: 10px; margin-left: 10px;">
						一键抠图
					</u-button>

					<!-- <u-button @click="showPictureEdit = true" type="primary" size="mini" plain
						style="margin-top: 10px; margin-left: 10px;">
						编辑图片
					</u-button> -->
				</view>
			</view>

			<view class="yy-card">
			</view>

			<view class="yy-card">
				<u-form-item label="名称" borderBottom ref="name" class="form-text">
					<u--input v-model="clothesInfo.name" border="none" inputAlign="right"></u--input>
				</u-form-item>

				<u-form-item label="类别" borderBottom ref="sub_category" class="form-text" @click="SelectCategories">
					<u--text :text="clothesInfo.category_name" align="right" size=15 suffixIcon="arrow-right"
						margin="10px" style="margin-right: 10rpx"></u--text>
				</u-form-item>

				<u-form-item label="季节" borderBottom ref="seasons" class="form-text" @click="SelectSeason">
					<view style="padding: 0 10px 10px 0" v-for="(item, index) in clothesInfo.season_names" :key="index">
						<u--text :text="item" align="left" size=15 margin="10px"></u--text>
					</view>
				</u-form-item>

				<u-form-item label="厚度" borderBottom ref="thickness" class="form-text" @click="SelectThickness">
					<u--text :text="clothesInfo.thickness_name" align="right" size=15 suffixIcon="arrow-right"
						margin="10px" style="margin-right: 10rpx"></u--text>
				</u-form-item>

				<u-form-item label="颜色" borderBottom ref="colors" class="form-text" @click="SelectColors">
					<view style="padding: 0 10px 10px 0" v-for="(item, index) in clothesInfo.color_names" :key="index">
						<u--text :text="item" align="left" size=15 margin="10px"></u--text>
					</view>
				</u-form-item>

				<u-form-item label="收纳位置" :borderBottom="false" ref="storage_location" class="form-text"
					@click="SelectLocation">
					<u--text :text="clothesInfo.storage_location_name" align="right" size=15 suffixIcon="arrow-right"
						margin="10px" style="margin-right: 10rpx"></u--text>
				</u-form-item>
			</view>

			<view class="yy-card">
				<u-form-item label="材质" borderBottom ref="sizes" class="form-text" @click="SelectMaterial">
					<view style="padding: 0 10px 10px 0" v-for="(item, index) in clothesInfo.materials" :key="index">
						<u--text :text="Number(item.percentage) + item.material_name" align="left" size=15
							margin="10px"></u--text>
					</view>
				</u-form-item>

				<u-form-item label="品牌" borderBottom ref="brand" class="form-text" @click="SelectBrand">
					<u--text :text="clothesInfo.brand_name" align="right" size=15 suffixIcon="arrow-right" margin="10px"
						style="margin-right: 10rpx"></u--text>
				</u-form-item>

				<u-form-item label="价格" borderBottom ref="price" class="form-text">
					<u--input v-model="clothesInfo.price" border="none" inputAlign="right" type="number"></u--input>
				</u-form-item>

				<u-form-item label="尺码" borderBottom ref="sizes" class="form-text" @click="SelectSize">
					<view style="padding: 0 10px 10px 0" v-for="(item, index) in clothesInfo.size_names" :key="index">
						<u--text :text="item" align="left" size=15 margin="10px"></u--text>
					</view>
				</u-form-item>

				<u-form-item label="链接" borderBottom ref="purchase_link" class="form-text">
					<u--input v-model="clothesInfo.purchase_link" border="none" inputAlign="right"></u--input>
				</u-form-item>

				<u-form-item label="购买日期" :borderBottom="false" ref="purchase_date" class="form-text"
					@click="SelectDate">
					<view> {{ clothesInfo.purchase_date }} </view>
				</u-form-item>
				<!-- 			<u-form-item label="购买日期" :borderBottom="false" ref="purchase_date"
				class="form-text" @click="SelectDate"
			>
				<u--text :text="clothesInfo.purchase_date" align="right" size=15
					suffixIcon="arrow-right" margin="10px" style="margin-right: 10rpx"></u--text>
			</u-form-item> -->
			</view>

			<view class="yy-card">
				<u-form-item label="标签" :borderBottom="false" ref="tags" class="form-text" @click="SelectTag">
					<view style="padding: 0 10px 10px 0" v-for="(item, index) in clothesInfo.tag_names" :key="index">
						<u--text :text="item" align="left" size=15 margin="10px"></u--text>
					</view>
				</u-form-item>
			</view>

			<view class="yy-card">
				<u-form-item label="备注" :borderBottom="false" ref="notes" class="form-text">
					<u--input v-model="clothesInfo.notes" border="none" inputAlign="right"></u--input>
				</u-form-item>
			</view>

			<!--view class="yy-card">
			<u-form-item label="其他图片" :borderBottom="false" ref="other_images">
				<u-upload
					:fileList="clothesInfo.other_images"
					@afterRead="afterRead"
					@delete="deletePic"
					name="1"
					multiple
					:maxCount="3"
					style="display: flex; flex-wrap: wrap; align-content: flex-end;"
				></u-upload>
			</u-form-item>
		</view-->

			<view class="yy-card">
				<u-form-item label="穿着日" :borderBottom="false" ref="record"> </u-form-item>
				<view style="display:flex">
					<view style="padding: 0 10px 10px 0" v-for="(item, index) in clothesInfo.records" :key="index">
						<u--text :text="item" align="left" size=15 margin="10px"></u--text>
					</view>
				</view>
			</view>
		</u--form>
		<u-button v-if="clothesInfo.id && clothesInfo.id > 0" type="error" text="删除当前衣服" @click="delClothes">
		</u-button>

		<!-- 分类选项（分类-子分类） -->
		<u-popup :show="showCategorySelector" position="bottom" @close="showCategorySelector = false">
			<view style="height: 300px; overflow-y: auto;">
				<tree-list :list="categoriesOptions" @change="CategoryChanged"></tree-list>
			</view>
		</u-popup>

		<!-- 季节（多选） -->
		<u-popup :show="showSeasonSelector" position="bottom" @close="showSeasonSelector = false">
			<view style="height: 150px; overflow-y: auto;">
				<u-checkbox-group v-model="clothesInfo.seasons" placement="column" @change="SeasonChanged"
					style="margin-top: 10px;">
					<u-checkbox v-for="(item, index) in seasonOptions" :key="item.id" :label="item.name" :name="item.id"
						style="margin: 8px 0 8px 20px;">
					</u-checkbox>
				</u-checkbox-group>
			</view>
		</u-popup>

		<!-- 厚度（单选） -->
		<u-popup :show="showThicknessSelector" position="bottom" @close="showThicknessSelector = false">
			<view style="height: 150px; overflow-y: auto;">
				<u-radio-group v-model="clothesInfo.thickness" placement="column" style="margin-top: 10px;">
					<u-radio :customStyle="{ marginBottom: '8px' }" v-for="(item, index) in thicknessOptions"
						:key="index" :label="item.name" :name="item.id" @change="ThicknessChanged"
						style="margin: 8px 0 8px 20px;">
					</u-radio>
				</u-radio-group>
			</view>
		</u-popup>

		<!-- 颜色（多选） -->
		<u-popup :show="showColorSelector" position="bottom" @close="showColorSelector = false">
			<view style="height: 150px; overflow-y: auto;">
				<u-checkbox-group v-model="clothesInfo.colors" placement="column" @change="ColorChanged"
					style="margin-top: 10px;">
					<u-checkbox v-for="(item, index) in colorOptions" :key="item.id" :label="item.name" :name="item.id"
						style="margin: 8px 0 8px 20px;">
					</u-checkbox>
				</u-checkbox-group>
			</view>
		</u-popup>

		<!-- 位置（单选） -->
		<u-popup :show="showLocationSelector" position="bottom" @close="showLocationSelector = false">
			<view style="height: 150px; overflow-y: auto;">
				<u-radio-group v-model="clothesInfo.storage_location" placement="column" style="margin-top: 10px;">
					<u-radio :customStyle="{ marginBottom: '8px' }" v-for="(item, index) in locationOptions"
						:key="index" :label="item.name" :name="item.id" @change="LocationChanged"
						style="margin: 8px 0 8px 20px;">
					</u-radio>
				</u-radio-group>
			</view>
		</u-popup>

		<!-- 品牌（单选） -->
		<u-popup :show="showBrandSelector" position="bottom" @close="showBrandSelector = false">
			<view style="height: 300px; overflow-y: auto;">
				<u-radio-group v-model="clothesInfo.brand" placement="column" style="margin-top: 10px;">
					<u-radio :customStyle="{ marginBottom: '8px' }" v-for="(item, index) in brandOptions" :key="index"
						:label="item.name" :name="item.id" @change="BrandChanged" style="margin: 8px 0 8px 20px;">
					</u-radio>
				</u-radio-group>
			</view>
		</u-popup>

		<!-- 尺码选项（多选） -->
		<u-popup :show="showSizeSelector" position="bottom" @close="showSizeSelector = false">
			<view style="height: 300px; overflow-y: auto;">
				<view style="display:flex; justify-content: space-between; margin: 10px 5px;">
					<text> 尺码选项 </text>
					<text @click="showSizeSelector = false"> 确认 </text>
				</view>
				<view v-for="(sizetype, index) in sizeOptions" :key="index" style="margin: 20px 0">
					<u--text :text="sizetype.name" size=15 style="margin: 10px 10px"></u--text>
					<view
						style="display:flex; justify-content: flex-start; margin: 10px 15px; align-content: flex-start;">
						<view v-for="size in sizetype.children" :key="size.id" style="margin-right: 10px">
							<u-tag :text="size.name" :plain="!size.checked" type="warning" :name="size.id"
								:key="refreshSize" @click="SizeChanged(size)">
							</u-tag>
						</view>
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 日期选择 -->
		<u-datetime-picker :show="showDateSelector" v-model="timestamp" :minDate="1262275200000" :key="timestamp"
			mode="date" @confirm="DateChanged" @cancel="showDateSelector = false"></u-datetime-picker>

		<!-- 标签选项 -->
		<u-popup :show="showTagSelector" position="bottom" @close="showTagSelector = false">
			<view style="height: 300px; overflow-y: auto;">
				<view style="display:flex; justify-content: space-between; margin: 10px 5px;">
					<text> 标签选项 </text>
					<text @click="showTagSelector = false"> 确认 </text>
				</view>
				<view v-for="(tagtype, index) in tagOptions" :key="index" style="margin: 20px 0">
					<u--text :text="tagtype.name" size=15 style="margin: 10px 10px"></u--text>
					<view
						style="display:flex; justify-content: flex-start; margin: 10px 15px; align-content: flex-start;">
						<view v-for="tag in tagtype.children" :key="tag.id" style="margin-right: 10px">
							<u-tag :text="tag.name" :plain="!tag.checked" type="warning" :name="tag.id"
								:key="refreshTag" @click="TagChanged(tag)">
							</u-tag>
						</view>
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 材质选项 -->
		<u-popup :show="showMaterialSelector" position="bottom" @close="showMaterialSelector = false">
			<view style="height: 300px; overflow-y: auto;">
				<view style="display:flex; justify-content: space-between; margin: 10px 5px;">
					<text> 材质选项 </text>
					<text @click="showMaterialSelector = false"> 确认 </text>
				</view>

				<view style="height: 150px; overflow-y: auto;">
					<view v-for="(item, index) in materialOptions" :key="item.id"
						style="margin-top: 10px; display: flex; flex-direction: row; align-items: center;">
						<view style="display:flex; height: 20px" @click="MaterialChanged(item)">
							<span v-if="clothesInfo.materials.find(mat => mat.material_id === item.id)"
								class="iconfont icon-checkbox-xuanzhong"
								style="font-size: 20px; padding-right: 5px"></span>
							<span v-else class="iconfont icon-checkbox-weixuan"
								style="font-size: 20px; padding-right: 5px"></span>
							<span>{{ item.name }}</span>
						</view>
						<u--input v-if="clothesInfo.materials.find(mat => mat.material_id === item.id)"
							v-model="clothesInfo.materials.find(mat => mat.material_id === item.id).percentage"
							border="bottom" type="number" style="width: 50px; margin: 0 0 -2px 20px; padding: 0"
							@input="MaterialPercentageChanged(item.id, $event)"></u--input>
					</view>
				</view>

				<!-- 			<view v-for="(material, index) in materialOptions" :key="index" style="margin: 20px 0">
				<u--text :text="material.name" size=15 style="margin: 10px 10px"></u--text>
				<view style="display:flex; justify-content: flex-start; margin: 10px 15px; align-content: flex-start;">
					<view v-for="material in material.children" :key="material.id" style="margin-right: 10px">
						<u-tag :text="material.name" :plain="!material.checked" type="warning" :name="material.id" :key="refreshMaterial"
							@click="MaterialChanged(material)">
						</u-tag>
					</view>
				</view>
			</view> -->

			</view>
		</u-popup>

		<!-- 图片编辑 -->
		<!-- <u-popup :show="showPictureEdit" position="bottom" @close="showPictureEdit = false" :overlay="true">
			<eraser-component :maskColor="clothesInfo.main_image" mask-color="#999999" />
		</u-popup> -->
	</view>

	</view>
</template>

<script>
import clothes from '@/api/clothes.js'
import ImageEraser from '@/components/eraser.vue'
export default {
	components: {
		ImageEraser,
	},
	data() {
		return {
			mode: "新增衣服",
			clothesInfo: {
				// "id": 1,
				"main_image": "",
				"name": "新衣服",
				"price": "0",
				"purchase_link": "",
				"notes": "",
				"sub_category": 0,
				"colors": [],
				"seasons": [],
				"sizes": [],
				"materials": [],
				"tags": [],
				"other_images": []
			},
			refreshKey: 0,

			mainImageKey: 0,
			showPictureEdit: false,
			tmpFile: "",		//临时图片（未保存到后台的）

			showCategorySelector: false,
			categoriesOptions: [],

			showSeasonSelector: false,
			seasonOptions: [],

			showThicknessSelector: false,
			thicknessOptions: [],

			showColorSelector: false,
			colorOptions: [],

			showLocationSelector: false,
			locationOptions: [],

			showMaterialSelector: false,
			materialOptions: [],

			showBrandSelector: false,
			brandOptions: [],

			showSizeSelector: false,
			sizeOptions: [],
			refreshSize: 1,

			showTagSelector: false,
			tagOptions: [],
			refreshTag: 1,

			showDateSelector: false,
			timestamp: 1530403200000,

			fileList1: [],
			season: []
		}
	},
	onLoad: function (data) {
		if (!data.cloth_id) {
			delete this.clothesInfo.id;
		}
		if (!data.cloth_id || data.cloth_id.length == 0) {
			this.mode = "新增衣服";
		}
		else {
			this.mode = "修改衣服信息";
		}
		// 分类
		clothes.get_categories_list().then(res => {
			this.categoriesOptions = res;
		})
		// 季节
		clothes.common.get_objects('season').then(res => {
			this.seasonOptions = res;
		})
		// 厚度
		clothes.common.get_objects('thickness').then(res => {
			this.thicknessOptions = res;
		})
		// 颜色
		clothes.common.get_objects('colors').then(res => {
			this.colorOptions = res;
		})
		// 位置
		clothes.common.get_objects('storage-locations').then(res => {
			this.locationOptions = res;
		})
		// 材质
		clothes.common.get_objects('materials').then(res => {
			this.materialOptions = res;
		})
		// 品牌
		clothes.common.get_objects('brands').then(res => {
			this.brandOptions = res;
		})
		// 尺码
		clothes.get_size_list().then(res => {
			this.sizeOptions = res;
		})
		// 标签
		clothes.get_tag_list().then(res => {
			this.tagOptions = res;
		})
		if (!data.cloth_id) {
			return;
		}
		clothes.common.get_object('clothes', data.cloth_id).then(res => {
			this.clothesInfo = res;
			this.clothesInfo.main_images = []
			if (this.clothesInfo.main_image) {
				this.clothesInfo.main_images.push({ url: this.clothesInfo.main_image })
			}
		});
		this.tmpFile = "";
	},
	methods: {
		goBack() {
			// 返回逻辑
			uni.navigateBack({
				delta: 1
			});
		},

		// 保存按钮
		async onSaveClothes() {
			// 保存确认必填项
			if (!this.clothesInfo.name || this.clothesInfo.name.length == 0) {
				uni.showToast({
					title: '请输入衣服名称',
					icon: 'none'
				});
				throw new Error('衣服名称不能为空');
			}
			if (!this.clothesInfo.sub_category) {
				uni.showToast({
					title: '请选择分类',
					icon: 'none'
				});
				throw new Error('分类不能为空');
			}
			// 删除后端返回的图片字段，避免调用保存main_image的字段
			delete this.clothesInfo.main_image;

			// 修改逻辑
			if (this.clothesInfo.id) {
				clothes.common.update_object('clothes', this.clothesInfo.id, this.clothesInfo).then(res => { })
			} else {
				// 新增逻辑【先新增，再上传图片】
				clothes.common.create_object('clothes', this.clothesInfo).then(res => {
				}).catch(res => {
					if (res.statusCode == 201) {
						this.clothesInfo.id = res.data.id;
						if (this.tmpFile) {
							this.blobUrlToBase64(this.tmpFile.url).then(base64 => {
								clothes.common.update_main_image('clothes', this.clothesInfo.id,
									this.tmpFile.name, base64).then(res => {
										uni.showToast({
											title: '保存成功',
											icon: 'success'
										});
										uni.navigateBack({
											delta: 1
										});
									})
							})

						}
					}
				})
			}
		},

		// 删除图片
		deleteMainImage(event) {
			this.clothesInfo.main_images = [];
			this.mainImageKey++;
		},
		// 将url读取为base64
		// blobUrlToBase64(blobUrl) {
		// 	return new Promise((resolve, reject) => {
		// 		const xhr = new XMLHttpRequest();
		// 		xhr.open('GET', blobUrl);
		// 		xhr.responseType = 'blob'; // 指定响应类型为Blob
		// 		xhr.onload = function () {
		// 			if (this.status === 200) {
		// 				const blob = this.response;
		// 				const reader = new FileReader();
		// 				reader.onloadend = () => resolve(reader.result); // 获取Data URL（包含Base64）
		// 				reader.onerror = reject;
		// 				reader.readAsDataURL(blob); // 将Blob读取为Data URL
		// 			} else {
		// 				reject(new Error('Failed to fetch blob'));
		// 			}
		// 		};
		// 		xhr.onerror = reject;
		// 		xhr.send();
		// 	});
		// },
		// 将url读取为base64
		blobUrlToBase64(blobUrl) {
			function mimetotype(filePath) {
				const extension = filePath.split('.').pop().toLowerCase();
				switch (extension) {
				case 'jpg':
				case 'jpeg':
					return 'image/jpeg';
				case 'png':
					return 'image/png';
				case 'gif':
					return 'image/gif';
				case 'svg':
					return 'image/svg+xml';
				// 可以根据需要添加更多的文件类型
				default:
					return 'application/octet-stream';
				}
			}
			return new Promise((resolve, reject) => {
				// 检查是否是本地文件路径
				if (blobUrl.startsWith('file://')) {
					// App 环境（使用 HTML5+ API）
					const path = blobUrl.replace('file://', '');
					const mime = mimetotype(path);
					plus.io.resolveLocalFileSystemURL(
						blobUrl,
						(entry) => {
							entry.file((file) => {
								const reader = new plus.io.FileReader();
								reader.onloadend = (e) => {
									let base64 = e.target.result.split(',')[1]; // 提取 base64 编码部分
									resolve(`data:${mime};base64,${base64}`);
								}
								reader.readAsDataURL(file, 'base64');
							});
						},
						(err) => reject(`App 路径解析失败: ${err.message}`)
					);
				} else {
					uni.request({
						url: blobUrl,
						method: 'GET',
						responseType: 'arraybuffer', // 指定响应类型为ArrayBuffer
						success: (res) => {
							if (res.statusCode === 200) {
								const arrayBuffer = res.data;
								const base64 = uni.arrayBufferToBase64(arrayBuffer);
								resolve(`data:image/jpeg;base64,${base64}`); // 这里假设是jpeg格式，根据实际情况调整
							} else {
								reject(new Error('Failed to fetch blob'));
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				}
			})
		},
		// 新增图片
		async afterReadMainImage(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file)
			// 临时保存，用于后续保存文件
			this.tmpFile = lists[0];
			// 刷新界面显示
			this.clothesInfo.main_images = [{
				url: lists[0].url
			}];
			this.mainImageKey++;

			if (this.clothesInfo.id) {
				// 将文件信息转换为base64
				const base64 = await this.blobUrlToBase64(this.tmpFile.url);
				if (!this.tmpFile.name) {
					this.tmpFile.name = this.tmpFile.url.split('/').pop(); // 获取文件名
				}
						
				clothes.common.update_main_image('clothes', this.clothesInfo.id, this.tmpFile.name, base64)
					.then(res => {
						console.log(res);
						
						this.tmpFile = "";
						uni.showToast({
							title: '上传成功',
							icon: 'success'
						});
					})
					.catch(res => {
						uni.showToast({
							title: '上传失败',
							icon: 'error'
						});
					})
			}
		},
		// 一键抠图
		async removeBackground() {
			// 检测是否有id，没有则先保存
			if (!this.clothesInfo.id) {
				uni.showToast({
					title: '请先保存衣服',
					icon: 'none'
				});
				return;
			}
			// 检测是否有图片
			if (!this.clothesInfo.main_images || this.clothesInfo.main_images.length == 0) {
				uni.showToast({
					title: '请先上传图片',
					icon: 'none'
				});
				return;
			}
			uni.showLoading({ title: '处理中...' });

			let base64In = await this.blobUrlToBase64(this.clothesInfo.main_images[0].url);
			// 调用接口，去除图片背景
			let removeRes = await uni.request({
				url: 'https://api.remove.bg/v1.0/removebg',
				method: 'POST',
				header: {
					'X-Api-Key': 'MTshQXEMwPE34DLtouH2EDx4'
				},
				responseType: 'arraybuffer',		//文件类型
				data: {
					// image_url: this.clothesInfo.main_images[0].url, // 图片URL
					image_file_b64: base64In,
					size: 'auto' // 自动调整大小
				},
			})
			uni.hideLoading();
			if (removeRes.statusCode == 200) {
				// 将Base64图片数据转换为临时文件路径
				const base64 = uni.arrayBufferToBase64(removeRes.data);
				clothes.common.update_main_image('clothes', this.clothesInfo.id, 'image.png', base64)
					.then(res => {
						this.clothesInfo.main_images = []
						if (res.main_image) {
							this.clothesInfo.main_images.push({ url: res.main_image })
						}
						this.mainImageKey++;
						uni.showToast({ title: '去背景成功' });
					})
					.catch(res => {
						uni.showToast({ title: '去背景失败', icon: 'none' });
					});
			}
			else {
				uni.showToast({ title: '去背景失败', icon: 'none' });
			}
		},

		// 选择分类
		SelectCategories() {
			this.categoriesOptions.forEach(item => {
				item.children.forEach(subitem => {
					if (subitem.id == this.clothesInfo.sub_category) {
						subitem.checked = true;
						item.isOpen = true;
					} else {
						subitem.checked = false;
					}
				});
			});
			this.showCategorySelector = true;
		},
		CategoryChanged(category, subcategory) {
			this.clothesInfo.category_name = category.name + '-' + subcategory.name;
			this.clothesInfo.sub_category = subcategory.id;
			this.showCategorySelector = false;
		},

		// 选择季节
		SelectSeason() {
			this.showSeasonSelector = true;
		},
		SeasonChanged(seasons) {
			let season_names = [];
			this.seasonOptions.forEach(item => {
				if (seasons.includes(item.id)) {
					season_names.push(item.name);
				}
			});
			this.clothesInfo.season_names = season_names;
		},

		// 选择厚度
		SelectThickness() {
			this.showThicknessSelector = true;
		},
		ThicknessChanged(thickness_id) {
			this.clothesInfo.thickness = thickness_id;
			this.thicknessOptions.forEach(item => {
				if (item.id == thickness_id) {
					this.clothesInfo.thickness_name = item.name;
				}
			});
			this.showThicknessSelector = false;
		},

		// 选择颜色
		SelectColors() {
			this.showColorSelector = true;
		},
		ColorChanged(colors) {
			let color_names = [];
			this.colorOptions.forEach(item => {
				if (colors.includes(item.id)) {
					color_names.push(item.name);
				}
			});
			this.clothesInfo.color_names = color_names;
		},

		// 选择位置
		SelectLocation() {
			this.showLocationSelector = true;
		},
		LocationChanged(location_id) {
			this.clothesInfo.storage_location = location_id;
			this.locationOptions.forEach(item => {
				if (item.id == location_id) {
					this.clothesInfo.storage_location_name = item.name;
				}
			});
			this.showLocationSelector = false;
		},

		// 选择材质
		SelectMaterial() {
			this.showMaterialSelector = true;
		},
		MaterialPercentageChanged(materialId, value) {
			// 更新材料百分比
			const material = this.clothesInfo.materials.find(mat => mat.material_id === materialId);
			if (material) {
				material.percentage = Number(value);
			}
		},
		MaterialChanged(material) {
			let find = false
			for (let index = 0; index < this.clothesInfo.materials.length; index++) {
				let ele = this.clothesInfo.materials[index];
				if (ele.material_id === material.id) {
					this.clothesInfo.materials.splice(index, 1);
					find = true
					break;
				}
			}
			if (!find) {
				this.clothesInfo.materials.push({
					material_id: material.id,
					material_name: material.name,
					percentage: 0
				})
			}
		},

		// 选择品牌
		SelectBrand() {
			this.showBrandSelector = true;
		},
		BrandChanged(brand_id) {
			this.clothesInfo.brand = brand_id;
			this.brandOptions.forEach(item => {
				if (item.id == brand_id) {
					this.clothesInfo.brand_name = item.name;
				}
			});
			this.showBrandSelector = false;
		},

		// 选择尺码
		SelectSize() {
			this.sizeOptions.forEach(item => {
				item.children.forEach(subitem => {
					if (this.clothesInfo.sizes.includes(subitem.id)) {
						subitem.checked = true;
					} else {
						subitem.checked = false;
					}
				});
			});
			this.showSizeSelector = true;
		},
		SizeChanged(size) {
			size.checked = !size.checked;
			this.refreshSize++;
			if (size.checked) {
				this.clothesInfo.sizes.push(size.id);
			} else {
				let index = this.clothesInfo.sizes.indexOf(size.id);
				if (index > -1) {
					this.clothesInfo.sizes.splice(index, 1);
				}
			}

			let size_names = [];
			this.sizeOptions.forEach(item => {
				item.children.forEach(subitem => {
					if (this.clothesInfo.sizes.includes(subitem.id)) {
						size_names.push(subitem.name);
					}
				});
			});
			this.clothesInfo.size_names = size_names;
		},

		SelectDate() {
			let a = new Date(this.clothesInfo.purchase_date);
			let t = a.getTime();
			this.timestamp = t;

			this.showDateSelector = true;
		},
		// 选择日期
		DateChanged($event) {
			const timestamp = $event.value;
			const date = new Date(timestamp);
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			this.clothesInfo.purchase_date = `${year}-${month}-${day}`;

			this.showDateSelector = false;
			// this.clothesInfo.purchase_date = $event.detail.value;
		},

		// 选择标签
		SelectTag() {
			this.tagOptions.forEach(item => {
				item.children.forEach(subitem => {
					if (this.clothesInfo.tags.includes(subitem.id)) {
						subitem.checked = true;
					} else {
						subitem.checked = false;
					}
				});
			});
			this.showTagSelector = true;
		},
		TagChanged(tag) {
			tag.checked = !tag.checked;
			this.refreshTag++;
			if (tag.checked) {
				this.clothesInfo.tags.push(tag.id);
			} else {
				let index = this.clothesInfo.tags.indexOf(tag.id);
				if (index > -1) {
					this.clothesInfo.tags.splice(index, 1);
				}
			}

			let tag_names = [];
			this.tagOptions.forEach(item => {
				item.children.forEach(subitem => {
					if (this.clothesInfo.tags.includes(subitem.id)) {
						tag_names.push(subitem.name);
					}
				});
			});
			this.clothesInfo.tag_names = tag_names;
		},

		delClothes() {
			uni.showModal({
				title: '提示',
				content: '确定要删除该衣服吗？',
				success: (res) => {
					if (res.confirm) {
						clothes.common.delete_object('clothes', this.clothesInfo.id)
							.then(res => { })
							.catch(res => {
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
								uni.navigateBack({
									delta: 1
								});
							})
					}
				}
			});
		}

	},
}
</script>

<style scoped>
@import '@/static/fonts/iconfont.css'

.container {
	padding: 10px 5px;
}

.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 10px;
	margin: 5px 5px;
	/* background-color: #f8f8f8; */
}

/deep/ .u-upload__default-slot .u-upload__default-slot--empty-list {
	display: flex;
	flex-direction: row-reverse;
}

.yy-card {
	margin: 10px 0;
	background-color: #f8f8f8;
	padding: 0 15px;
	border-radius: 10px;
}

/deep/ .u-upload {
	.u-upload__default-slot--empty-list {
		display: flex;
		flex-direction: row-reverse;
	}
}

/deep/ .u-upload__button {
	margin: 0;
}

/deep/ .form-text {
	.u-form-item__body {
		height: 40px;
	}
}

/deep/ .u-form-item__body__left {
	width: 100px !important;
}

/deep/ .u-form-item__body__right__content__slot {
	display: flex;
	justify-content: flex-end;
}

.u-popup__content {
	touch-action: none;
	/* 禁用触摸滚动 */
}
</style>
